<template>
  <el-date-picker
    v-model="dateRangeValue"
    type="daterange"
    range-separator="到"
    start-placeholder="开始时间"
    end-placeholder="结束时间"
    unlink-panels
    @calendar-change="calendarChange"
    @change="dateRangeChange"
    :disabled-date="disabledDate"
  />
</template>
<script setup lang="ts">
import { ref } from "vue";

export interface dateRangeType {
  dateRangeValue;
}
const emits = defineEmits(["dateRangeChange"]);
type Props = {
  startDate?: Date;
  endDate?: Date;
};

const props = withDefaults(defineProps<Props>(), {
  startDate: () => {
    const startDate = new Date();
    startDate.setTime(startDate.getTime() - 3600 * 1000 * 24 * 7);
    // console.log("startDate:", startDate);
    return startDate;
  },
  endDate: () => {
    const date = new Date();
    date.setTime(date.getTime() - 3600 * 1000 * 24);
    // console.log("startDate:", startDate);
    return date;
  }
});

const dateRangeValue = ref<[Date, Date]>([props.startDate, props.endDate]);

const firstDate = ref(null);

function calendarChange(date) {
  // console.log("calendarChange:", date);
  if (date[1] === null) {
    firstDate.value = date[0];
  } else {
    firstDate.value = null;
  }
}

function dateRangeChange() {
  emits("dateRangeChange", dateRangeValue.value);
}

const disabledDate = (time: Date) => {
  // 31536000000 一年的毫秒数  15768000000 半年毫秒数
  const timeNum = time.getTime();
  if (firstDate.value) {
    // console.log("disabledDate timeNum:", timeNum);
    return (
      timeNum > Date.now() ||
      timeNum < firstDate.value.getTime() - 15768000000 ||
      timeNum > firstDate.value.getTime() + 15768000000
    );
  } else {
    return timeNum > Date.now();
  }
};

defineExpose({
  dateRangeValue
});
</script>
